package com.application.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseFragment<V extends ViewDataBinding, VM extends ViewModel> extends Fragment {
    protected V binding;
    public VM viewModel;
    private int viewModelId;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initViewDataBinding(inflater, container, savedInstanceState);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        initViewObservable();
    }

    private void initViewDataBinding(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, initLayoutId(), container, false);
        viewModelId = initVariableId();
        viewModel = initViewModel();
        if (viewModel == null) {
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType) {
                Class<VM> modelClass = (Class<VM>) ((ParameterizedType) type).getActualTypeArguments()[1];
                viewModel = new ViewModelProvider(this).get(modelClass);
            }
        }
        binding.setVariable(viewModelId, viewModel);
        binding.setLifecycleOwner(this);
    }

    /**
     * 子类必须实现：返回布局资源ID
     */
    @LayoutRes
    protected abstract int initLayoutId();

    /**
     * 子类必须实现：返回ViewModel在布局中的变量ID（BR.xxx）
     */
    protected abstract int initVariableId();

    /**
     * 子类可选实现：自定义ViewModel初始化（默认通过反射创建）
     */
    protected VM initViewModel() {
        return null;
    }

    /**
     * 初始化数据
     */
    protected void initData() {
    }

    /**
     * 初始化ViewModel与View的观察者关系
     */
    protected void initViewObservable() {
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 解绑DataBinding，避免内存泄漏
        if (binding != null) {
            binding.unbind();
        }
    }
}
